package cn.gailvlun.gll.presentation.apartment.room;

import android.Manifest;
import android.app.Activity;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.bigkoo.pickerview.OptionsPickerView;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.PictureSelectorActivity;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import cn.gailvlun.gll.R;
import cn.gailvlun.gll.databinding.ActivityCreateRoomBinding;
import cn.gailvlun.gll.mgr.UploadMgr;
import cn.gailvlun.gll.net.apartment.room.CreateRoomReq;
import cn.gailvlun.gll.net.apartment.room.Room;
import cn.gailvlun.gll.net.apartment.room.RoomTag;
import cn.gailvlun.gll.net.apartment.room.Task;
import cn.gailvlun.gll.presentation.apartment.room.vm.CreateRoomViewModel;
import cn.gailvlun.gll.presentation.apartment.task.TaskSettingActivity;
import cn.gailvlun.gll.presentation.base.BaseActivity;
import cn.gailvlun.gll.util.IsEmpty;
import cn.gailvlun.gll.util.LogUtil;
import cn.gailvlun.gll.util.ToastUtil;
import cn.gailvlun.gll.widget.NavigationBarView;
import io.reactivex.functions.Consumer;
import rx_activity_result2.Result;
import rx_activity_result2.RxActivityResult;



public class CreateRoomActivity extends BaseActivity {

    public static void openActivity(Context context) {
        Intent intent = new Intent(context, CreateRoomActivity.class);
        context.startActivity(intent);
    }

    public static void openActivity(Context context, int roomId) {
        Intent intent = new Intent(context, CreateRoomActivity.class);
        intent.putExtra("roomId", roomId);
        context.startActivity(intent);
    }

    private ActivityCreateRoomBinding mBinding;

    
    private int mHours = 1;

    
    public AMapLocationClient mLocationClient = null;
    
    public AMapLocationListener mLocationListener = new AMapLocationListener() {

        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() != 0) {
                    
                    return;
                }
                mBinding.tvCity.setText(aMapLocation.getCity());
            }
        }
    };

    public AMapLocationClientOption mOption = new AMapLocationClientOption() {
        {
            setLocationMode(AMapLocationMode.Hight_Accuracy);
            setOnceLocation(true);
            setNeedAddress(true);
            setLocationCacheEnable(false);
        }
    };

    public CreateRoomReq mCreateRoomReq = new CreateRoomReq();

    @Override
    protected void initComponent() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_create_room);
        mBinding.setPresenter(new Presenter());

        
        new RxPermissions(mContext)
                .request(Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            
                            mLocationClient = new AMapLocationClient(getApplicationContext());
                            
                            mLocationClient.setLocationListener(mLocationListener);
                            mLocationClient.setLocationOption(mOption);
                            mLocationClient.startLocation();
                        }
                        
                    }
                });
        

    }

    @Override
    protected void createHandler() {
        mBinding.nbv.setOnBackListener(new NavigationBarView.OnBackListener() {
            @Override
            public void onBack(NavigationBarView nb) {
                onBackPressed();
            }
        });
        mBinding.nbv.setOnMenuClickListener(new NavigationBarView.OnMenuClickListener() {
            @Override
            public void onMenuClick(NavigationBarView nb) {
                if (mViewModel.isModify()) {
                    if (mCreateRoomReq.getPic() == null) {
                        ToastUtil.showShort("请选择图片");
                        return;
                    }
                    if (IsEmpty.string(mBinding.etName.getText())
                            || mCreateRoomReq.getTag() == null || IsEmpty.string(mBinding.tvCity.getText())
                            || mCreateRoomReq.getMember_max() == null) {
                        ToastUtil.showShort("请填写所有字段");
                        return;
                    }
                    if (mBinding.etAnnouncement.getText().length() < 30) {
                        ToastUtil.showShort("房间简介不得小于30字");
                        return;
                    }
                    mCreateRoomReq.setName(mBinding.etName.getText().toString());
                    mCreateRoomReq.setCity(mBinding.tvCity.getText().toString());
                    mCreateRoomReq.setDesc(mBinding.etAnnouncement.getText().toString());

                    TimeSettingActivity.openActivity(mContext, mCreateRoomReq, roomId,Integer.valueOf(mBinding.tvDays.getText().toString()));
                } else {
                    if (mCreateRoomReq.getPic() == null) {
                        ToastUtil.showShort("请选择图片");
                        return;
                    }
                    if (IsEmpty.string(mBinding.etName.getText())
                            || mCreateRoomReq.getTag() == null || IsEmpty.string(mBinding.tvCity.getText())
                            || mCreateRoomReq.getMember_max() == null
                            || IsEmpty.string(mCreateRoomReq.getTasks())) {
                        ToastUtil.showShort("请填写所有字段");
                        return;
                    }

                    if (mBinding.etAnnouncement.getText().length() < 30) {
                        ToastUtil.showShort("房间简介不得小于30字");
                        return;
                    }

                    mCreateRoomReq.setName(mBinding.etName.getText().toString());
                    mCreateRoomReq.setCity(mBinding.tvCity.getText().toString());
                    mCreateRoomReq.setDesc(mBinding.etAnnouncement.getText().toString());

                    TimeSettingActivity.openActivity(mContext, mCreateRoomReq, mHours);
                }
            }
        });
    }

    private CreateRoomViewModel mViewModel;
    private Integer roomId;

    @Override
    protected void loadData(@Nullable Bundle savedInstanceState) {
        roomId = getIntent().getIntExtra("roomId", -1);

        mViewModel = ViewModelProviders.of(this).get(CreateRoomViewModel.class);

        if (roomId != -1) {
            mViewModel.setModify(true);
            Room room = mViewModel.getRoomById(roomId);
            
            mBinding.llAdd.setVisibility(View.GONE);
            Glide.with(mContext)
                    .load(room.getPic())
                    .into(mBinding.riv);
            mCreateRoomReq.setPic(room.getPic().replace("https://img.xiaogaijun.com/", ""));

            
            mBinding.etName.setText(room.getName());
            
            switch (room.getTag()) {
                case J:
                case B:
                case X:
                case T: {
                    mBinding.llEmotion.setVisibility(View.GONE);
                    mBinding.tvRoomType.setText(room.getTag().toString());
                    mCreateRoomReq.setTag(room.getTag());
                    break;
                }
                case D:
                case A:
                case L:
                case Y: {
                    mBinding.tvRoomType.setText(RoomTag.LOVE.toString());
                    mBinding.llEmotion.setVisibility(View.VISIBLE);
                    mBinding.tvEmotion.setText(room.getTag().toString());
                    mCreateRoomReq.setTag(room.getTag());
                    break;
                }
            }
            

            
            mBinding.tvMaxPeople.setText(room.getMember_max() + "人");
            mCreateRoomReq.setMember_max(room.getMember_max());
            if (room.getMember_min() > 0) {
                
                mBinding.tvMinPeople.setText(room.getMember_min() + "人");
                mBinding.llPeopleMin.setClickable(false);
                mBinding.llPeopleMin.setEnabled(false);
                mCreateRoomReq.setMember_min(room.getMember_min());
            }
            
            mBinding.llTask.setEnabled(false);
            ArrayList<Integer> tempIdList = new ArrayList<>();
            for (Task task : room.getTasks()) {
                tempIdList.add(task.getId());
            }
            String ids = TextUtils.join(",", tempIdList);
            mBinding.tvTask.setText(ids);

            if (tempIdList.size() > 0) {
                mBinding.tvDays.setText(String.valueOf(tempIdList.size()));
                mBinding.llDays.setClickable(false);
                mBinding.llDays.setEnabled(false);
            }
            
            mBinding.etAnnouncement.setText(room.getDesc());
        }
    }

    private void uploadImage(File file) {
        String photoObjectKey = UUID.randomUUID().toString() + "." + FileUtils.getFileExtension(file);
        UploadMgr.getInstance().upload(photoObjectKey, file.getPath(), new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                LogUtil.d("图片上传成功");
                mCreateRoomReq.setPic(request.getObjectKey());
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                
                mBinding.riv.setColorFilter(ContextCompat.getColor(mContext, R.color.paleGreyThree));
                mBinding.llAdd.setVisibility(View.VISIBLE);
                ToastUtil.showShort("图片上传失败，请重新选择");
            }
        });
    }

    private ArrayList<Integer> idList;
    private ArrayList<Integer> littleOwnerList;

    public class Presenter {
        public void onAddLittleOwner() {
            AddOwnerActivity.Companion.openActivity(mContext)
                    .subscribe(new Consumer<Result<Activity>>() {
                        @Override
                        public void accept(Result<Activity> activityResult) throws Exception {
                            if (activityResult.resultCode() == RESULT_OK) {
                                littleOwnerList = activityResult.data().getIntegerArrayListExtra("userId");
                                mBinding.tvLittleOwner.setText(littleOwnerList.size() + "人");
                                mCreateRoomReq.setSmall_host_list(littleOwnerList);
                            }
                        }
                    });
        }

        public void onSelectPhoto() {
            new RxPermissions(mContext)
                    .request(Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.CAMERA)
                    .subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(Boolean aBoolean) throws Exception {






                            
                            PictureSelector.create(mContext)
                                    .openGallery(PictureMimeType.ofImage())
                                    .maxSelectNum(1)
                                    .minSelectNum(1)
                                    .imageSpanCount(4)
                                    .selectionMode(PictureConfig.SINGLE)
                                    .previewImage(true)
                                    .isCamera(true)
                                    .imageFormat(PictureMimeType.PNG)
                                    .isZoomAnim(true)
                                    .sizeMultiplier(0.5f)
                                    .setOutputCameraPath("/camera")
                                    .previewEggs(true)
                                    .enableCrop(true)
                                    .withAspectRatio(16, 9)
                                    .compress(true)
                                    .cropCompressQuality(80)
                                    .minimumCompressSize(200);

                            RxActivityResult.on(mContext)
                                    .startIntent(new Intent(mContext, PictureSelectorActivity.class))
                                    .subscribe(new Consumer<Result<BaseActivity>>() {
                                        @Override
                                        public void accept(Result<BaseActivity> activityResult) throws Exception {
                                            if (activityResult.resultCode() == Activity.RESULT_OK) {
                                                List<LocalMedia> list = PictureSelector.obtainMultipleResult(activityResult.data());
                                                LocalMedia localMedia = list.get(0);

                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        mBinding.llAdd.setVisibility(View.GONE);
                                                    }
                                                });
                                                Glide.with(mContext)
                                                        .load(localMedia.getCompressPath())
                                                        .into(mBinding.riv);
                                                uploadImage(FileUtils.getFileByPath(localMedia.getCompressPath()));
                                            }
                                        }
                                    });
                        }
                    });
        }

        public void onRoomType() {
            KeyboardUtils.hideSoftInput(mContext);

            final List<RoomTag> tagList = Arrays.asList(RoomTag.J, RoomTag.B, RoomTag.X, RoomTag.T, RoomTag.LOVE);
            OptionsPickerView<RoomTag> pickerView = new OptionsPickerView.Builder(mContext, new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    mBinding.tvRoomType.setText(tagList.get(options1).toString());
                    if (options1 == 4) {
                        
                        mCreateRoomReq.setTag(null);
                        mBinding.tvEmotion.setText(null);
                        mBinding.llEmotion.setVisibility(View.VISIBLE);
                    } else {
                        mCreateRoomReq.setTag(tagList.get(options1));
                        mBinding.llEmotion.setVisibility(View.GONE);
                    }
                }
            }).build();
            pickerView.setPicker(tagList);
            pickerView.show();
        }

        public void onEmotionType() {
            KeyboardUtils.hideSoftInput(mContext);

            final List<RoomTag> tagList = Arrays.asList(RoomTag.D, RoomTag.A,
                    RoomTag.L, RoomTag.Y);
            OptionsPickerView<RoomTag> pickerView = new OptionsPickerView.Builder(mContext, new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    mCreateRoomReq.setTag(tagList.get(options1));
                    mBinding.tvEmotion.setText(tagList.get(options1).toString());
                }
            }).build();
            pickerView.setPicker(tagList);
            pickerView.show();
        }

        public void onPeopleMax() {
            KeyboardUtils.hideSoftInput(mContext);

            final List<String> tagList = Arrays.asList(getResources().getStringArray(R.array.apartment_people_max));
            OptionsPickerView<String> pickerView = new OptionsPickerView.Builder(mContext, new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    int maxPeople = (options1 + 2) * 10;
                    mBinding.tvMaxPeople.setText(maxPeople + "人");
                    mCreateRoomReq.setMember_max(maxPeople);
                }
            }).build();
            pickerView.setPicker(tagList);
            pickerView.show();
        }

        public void onPeopleMin() {
            KeyboardUtils.hideSoftInput(mContext);
            final List<String> tagList = Arrays.asList(getResources().getStringArray(R.array.apartment_people_min));
            OptionsPickerView<String> pickerView = new OptionsPickerView.Builder(mContext, new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    int minPeople = (options1 + 10);
                    mBinding.tvMinPeople.setText(minPeople + "人");
                    mCreateRoomReq.setMember_min(minPeople);
                }
            }).build();
            pickerView.setPicker(tagList);
            pickerView.show();
        }

        public void onTaskSetting() {
            
            TaskSettingActivity.openActivity(mContext, mHours, idList, new Consumer<Result<Activity>>() {
                @Override
                public void accept(Result<Activity> activityResult) throws Exception {
                    if (activityResult.data() != null) {
                        idList = activityResult.data().getIntegerArrayListExtra("idList");
                        if (!IsEmpty.list(idList)) {
                            
                            String ids = TextUtils.join(",", idList);
                            mBinding.tvTask.setText(ids);
                            mCreateRoomReq.setTasks(ids);
                        }
                    }
                }
            });
        }


        public void onPickDays() {
            KeyboardUtils.hideSoftInput(mContext);
            
            final List<Integer> hourList = new ArrayList<>();
            
            for (int i = 1; i <= 23; i++) {
                hourList.add(i);
            }
            
            for (int i = 1; i <= 7; i++) {
                hourList.add(i * 24);
            }
            final List<String> tagList = new ArrayList<>();
            for (Integer integer : hourList) {
                if (integer < 24) {
                    tagList.add(integer + "小时");
                } else {
                    tagList.add(integer / 24 + "天");
                }
            }

            OptionsPickerView<String> pickerView = new OptionsPickerView.Builder(mContext, new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    mBinding.tvDays.setText(tagList.get(options1).toString());

                    mHours = hourList.get(options1);

                    if (idList != null && idList.size() != TaskSettingActivity.getTaskNumberByHours(mHours)) {
                        idList.clear();
                        mBinding.tvTask.setText(null);
                        mCreateRoomReq.setTasks(null);
                    }
                }
            }).build();
            pickerView.setPicker(tagList);
            pickerView.show();

        }
    }

    private String getCompressedPath() {
        return getCacheDir().toString();
    }
}
